<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\service\UserService;

/**
 * 用户模型
 * 提供用户数据的数据库操作
 */
class User extends Model
{
    // 设置表名
    protected $name = 'customers';
    
    
    // 软删除
    protected $deleteTime = 'deleted_at';
    
    // 隐藏字段
    protected $hidden = ['password'];


    /**
     * 客户组关联
     */
    public function customerGroup()
    {
        return $this->hasOne(CustomerGroups::class, 'customer_group_id', 'id')->where('locale', 'zh_cn');
    }

    /**
     * 客户组描述关联
     */
    public function customerGroupDescription()
    {
        return $this->hasOne(CustomerGroupDescriptions::class, 'customer_group_id', 'id')->where('locale', 'zh_cn');
    }

    
    /**
     * 密码修改器 - 自动加密密码
     */
    public function setPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }
    
    /**
     * 状态获取器 - 格式化状态
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [1 => '正常', 0 => '禁用'];
        return $status[$data['status']] ?? '未知';
    }
    
    /**
     * 角色获取器 - 格式化角色
     */
    // public function getRoleTextAttr($value, $data)
    // {
    //     $roles = ['user' => '普通用户', 'admin' => '管理员'];
    //     return $roles[$data['role']] ?? '未知';
    // }
    
    /**
     * 根据用户名或邮箱查找用户
     */
    public static function findByUsernameOrEmail(string $username): ?User
    {
        return self::where('username', $username)
            ->whereOr('phone', $username)
            ->find();
    }
    
    /**
     * 验证密码
     */
    public function verifyPassword(string $password): bool
    {
        return password_verify($password, $this->password);
    }
    
    /**
     * 更新最后登录时间
     */
    public function updateLastLogin(): bool
    {
        $this->last_login = date('Y-m-d H:i:s');
        return $this->save();
    }
    
    /**
     * 检查用户是否可用
     */
    public function isAvailable(): bool
    {
        return $this->status == 1;
    }
    
    /**
     * 检查是否为管理员
     */
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }
    
    /**
     * 获取格式化的用户信息
     */
    public function getFormattedInfo(): array
    {
        return [];
        // return [
        //     'userId' => $this->id,
        //     'username' => $this->username,
        //     'nickname' => $this->nickname ?? '',
        //     'avatar' => $this->avatar ?? '',
        //     'email' => $this->email ?? '',
        //     'phone' => $this->phone ?? '',
        //     'role' => $this->role ?? 'user',
        //     'roleText' => $this->role_text,
        //     'status' => $this->status ?? 1,
        //     'statusText' => $this->status_text,
        //     'createTime' => $this->created_at ? $this->created_at->format('Y-m-d H:i:s') : '',
        //     'lastLogin' => $this->last_login ? $this->last_login->format('Y-m-d H:i:s') : ''
        // ];
    }
    
    /**
     * 获取当前用户信息（静态方法）
     */
    public static function getCurrentUser(): ?array
    {
        return UserService::getCurrentUser();
    }
    
    /**
     * 获取当前用户ID（静态方法）
     */
    public static function getCurrentUserId(): ?int
    {
        return UserService::getCurrentUserId();
    }
    
    /**
     * 检查当前用户是否已登录（静态方法）
     */
    public static function isLoggedIn(): bool
    {
        return UserService::isLoggedIn();
    }
    
    /**
     * 检查当前用户是否为管理员（静态方法）
     */
    public static function isCurrentUserAdmin(): bool
    {
        return UserService::isAdmin();
    }
    
    /**
     * 创建新用户
     */
    public static function createUser(array $data): User
    {
        return new self();
        // $user = new self();
        // $user->username = $data['username'];
        // $user->email = $data['email'] ?? '';
        // $user->password = $data['password']; // 会自动加密
        // $user->nickname = $data['nickname'] ?? $data['username'];
        // $user->avatar = $data['avatar'] ?? '';
        // $user->phone = $data['phone'] ?? '';
        // $user->role = $data['role'] ?? 'user';
        // $user->status = $data['status'] ?? 1;
        // $user->save();
        
        // return $user;
    }
    
    /**
     * 搜索用户
     */
    public static function searchUsers(array $params): array
    {
        return [];
        // $query = self::order('created_at', 'desc');
        
        // // 按用户名搜索
        // if (!empty($params['username'])) {
        //     $query->where('username', 'like', '%' . $params['username'] . '%');
        // }
        
        // // 按邮箱搜索
        // if (!empty($params['email'])) {
        //     $query->where('email', 'like', '%' . $params['email'] . '%');
        // }
        
        // // 按角色筛选
        // if (!empty($params['role'])) {
        //     $query->where('role', $params['role']);
        // }
        
        // // 按状态筛选
        // if (isset($params['status']) && $params['status'] !== '') {
        //     $query->where('status', $params['status']);
        // }
        
        // // 分页
        // $page = $params['page'] ?? 1;
        // $limit = $params['limit'] ?? 20;
        
        // return $query->paginate([
        //     'list_rows' => $limit,
        //     'page' => $page
        // ])->toArray();
    }


    public static function decUserBalance($userId,$sourceId=0,$amount=0,$remark='')
    {
        $uis = self::getCurrentUser();
        User::where('id',$userId)->dec('balance',(float)$amount)->update();
        UserAccountRecord::insert([
            'user_id' => $userId,
            'record_type' => 'balance',
            'change_type' => 2,
            'amount' => (float)$amount,
            'before_balance' => (float)$uis?(float)$uis['balance']:0,
            'relation_id' => 0,
            'source_type' => 'order',
            'source_id' => $sourceId,
            'remark' => $remark,
            'status' => 1,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // 增加用户余额
    public static function incUserBalance($userId,$sourceId=0,$amount=0,$remark='')
    {
        $uis = self::getCurrentUser();
        User::where('id',$userId)->inc('balance',(float)$amount)->update();
        UserAccountRecord::insert([
            'user_id' => $userId,
            'record_type' => 'balance',
            'change_type' => 1,
            'amount' => (float)$amount,
            'before_balance' => (float)$uis?(float)$uis['balance']:0,
            'relation_id' => 0,
            'source_type' => 'order',
            'source_id' => $sourceId,
            'remark' => $remark,
            'status' => 1,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}